﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Text;
using Telerik.Web.UI;

/// <summary>
/// Grid命令封装
/// </summary>
public class GridCommander
{
    /// <summary>
    /// 从当前行(添加/修改)提取值
    /// </summary>
    /// <param name="e"></param>
    /// <returns><seealso cref="HybridDictionary"/></returns>
    public static HybridDictionary ExtractValues(GridCommandEventArgs e)
    {
        HybridDictionary dict = new HybridDictionary();
        GridEditableItem editableItem = e.Item as GridEditableItem;
        if (editableItem != null)
        {
            editableItem.ExtractValues(dict);
        }
        return dict;
    }

    /// <summary>
    /// 合并多个主键值
    /// </summary>
    /// <param name="dataKeys"></param>
    /// <param name="selectedIndexes"></param>
    /// <returns></returns>
    public static string JoinValues(GridDataKeyArray dataKeys, GridIndexCollection selectedIndexes)
    {
        return JoinValues(dataKeys, selectedIndexes, ",");
    }

    /// <summary>
    /// 合并多个主键值
    /// </summary>
    /// <param name="dataKeys"></param>
    /// <param name="selectedIndexes"></param>
    /// <param name="separator"></param>
    /// <returns></returns>
    public static string JoinValues(GridDataKeyArray dataKeys, GridIndexCollection selectedIndexes, string separator)
    {
        int max = selectedIndexes.Count - 1;
        StringBuilder builder = new StringBuilder();
        object value = null;
        for (int i = 0; i <= max; i++)
        {
            foreach (object item in dataKeys[int.Parse(selectedIndexes[i])].Values)
            {
                value = item;
                break;
            }
            builder.Append(value.ToString());
            if (i < max)
                builder.Append(separator);
        }
        return builder.ToString();
    }

    /// <summary>
    /// 从当前行(添加/修改)提取值
    /// </summary>
    /// <param name="e"></param>
    /// <returns><seealso cref="SqlParameter[]"/></returns>
    public static SqlParameter[] ExtractAsSqlParameter(GridCommandEventArgs e)
    {
        HybridDictionary dict = ExtractValues(e);
        List<SqlParameter> parameters = new List<SqlParameter>(dict.Count);
        foreach (string key in dict.Keys)
        {
            parameters.Add(new SqlParameter(key, dict[key]));
        }
        return parameters.ToArray();
    }

    /// <summary>
    /// 从当前行(添加/修改)提取值
    /// </summary>
    /// <param name="e"></param>
    /// <param name="key">key</param>
    /// <returns>int</returns>
    public static string ExtractValue(GridCommandEventArgs e, string key)
    {
        HybridDictionary dict = ExtractValues(e);
        if (dict.Contains(key))
        {
            object value = dict[key];
            if (value != null)
                return value.ToString();
        }
        return string.Empty;
    }

    public static string ExtractAsInsertSql(GridCommandEventArgs e, params string[] excludeFields)
    {
        HybridDictionary dict = ExtractValues(e);
        StringBuilder builder = new StringBuilder();
        StringBuilder builder2 = new StringBuilder();
        int max = dict.Keys.Count - 1, i = 0;
        builder.Append("(");
        foreach (string key in dict.Keys)
        {
            if (isExcludeField(excludeFields, key))
            {
                i++;
                continue;
            }
            builder.AppendFormat("[{0}]", key);
            builder2.AppendFormat("@{0}", key);
            if (i++ < max)
            {
                builder.Append(",");
                builder2.Append(",");
            }
        }
        builder.Append(") values(");
        builder.Append(builder2.ToString());
        builder.Append(");");
        return builder.ToString();

    }

    static bool isExcludeField(string[] fields, string key)
    {
        if (fields == null)
            return false;
        foreach (string ef in fields)
        {
            if (string.Compare(key, ef, StringComparison.OrdinalIgnoreCase) == 0)
                return true;
        }
        return false;
    }

    public static string ExtractAsUpdateSql(GridCommandEventArgs e, string keyField, params string[] excludeFields)
    {
        HybridDictionary dict = ExtractValues(e);
        StringBuilder builder = new StringBuilder();
        int max = dict.Keys.Count - 1, i = 0;
        string where = string.Empty;
        builder.Append(" SET ");
        foreach (string key in dict.Keys)
        {
            if (isExcludeField(excludeFields, key))
            {
                i++;
                continue;
            }
            if (string.Compare(key, keyField, StringComparison.OrdinalIgnoreCase) == 0)
            {
                where = string.Format(" WHERE [{0}]=@{0};", key);
                i++;
            }
            else
            {
                builder.AppendFormat("[{0}]=@{0}", key);
                if (i++ < max)
                {
                    builder.Append(",");
                }
            }
        }
        if (!string.IsNullOrEmpty(where))
            builder.Append(where);
        return builder.ToString();
    }

    /// <summary>
    /// 插入数据
    /// </summary>
    /// <param name="e"></param>
    /// <param name="insertSql">sql语句</param>
    public static void Insert(GridCommandEventArgs e, string insertSql)
    {
        SqlHelper.Instance.ExecuteNonQuery(insertSql, GridCommander.ExtractAsSqlParameter(e));
    }

    /// <summary>
    /// 更新数据
    /// </summary>
    /// <param name="e"></param>
    /// <param name="updateSql">sql语句</param>
    public static void Update(GridCommandEventArgs e, string updateSql)
    {
        SqlHelper.Instance.ExecuteNonQuery(updateSql, GridCommander.ExtractAsSqlParameter(e));
    }

    public static void Delete(GridCommandEventArgs e, string deleteSql, string key)
    {
        SqlHelper.Instance.ExecuteNonQuery(deleteSql, new SqlParameter(key, ExtractValue(e, key)));
    }
}